package xyz.xtt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import xyz.xtt.admin.entity.TblUser;
import xyz.xtt.admin.entity.TblUserChainAccount;
import xyz.xtt.admin.mapper.UserMapper;
import xyz.xtt.admin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.xtt.admin.utils.MyAESUtil;
import xyz.xtt.admin.vo.UserVo;

import java.util.*;

/**
 * <p>
 * 用户基础信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TblUser> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Value("${config.oss_cdn_url}")
    private String CdnUrl;
    @Value("${config.default_female}")
    private String defaultFemale;
    @Value("${config.default_male}")
    private String defaultMale;

    public TblUser getUserByAppUserId(Long id){
        QueryWrapper<TblUser> query = new QueryWrapper<>();
        query.eq("app_user_id", id);
        return userMapper.selectOne(query);
    }

    public TblUser getUserByName(String name){
        QueryWrapper<TblUser> query = new QueryWrapper<>();
        query.eq("nickname", name);
        return userMapper.selectOne(query);
    }

    // 根据名称或者手机号 获取到用户信息
    public TblUser getUserByNameAndPhone(String name, String phone) throws Exception {
        QueryWrapper<TblUser> query = new QueryWrapper<>();

        if(StringUtils.isNotBlank(phone)) {
            phone = phone.startsWith("86") ? phone : "86" + phone;
            phone =  MyAESUtil.encrypt(phone);
            query.eq("phone", phone);
        }
        if (StringUtils.isNotBlank(name)) {
            query.eq("nickname", name);
        }

        String sqlSegment = query.getSqlSegment();

        if(sqlSegment == null || sqlSegment.trim().isEmpty()) {
            return null;
        }
        query.orderByDesc("id")
                .last("limit 1");
        return  userMapper.selectOne(query);
    }

    // 根据名称或者手机号 获取到用户信息
    public List<TblUser> getUserByPhone(List<String> phones){
        LambdaQueryWrapper<TblUser> query = new LambdaQueryWrapper<>();
        query.select(TblUser::getAppUserId, TblUser::getPhoneBk);
        query.in(TblUser::getPhoneBk, phones);
        String sqlSegment = query.getSqlSegment();
        if(sqlSegment == null || sqlSegment.trim().isEmpty()) {
            return null;
        }
        return  userMapper.selectList(query);
    }

    // 根据脱敏后的手机号 获取用户信息
    public TblUser getUserByPhone(String phone){
        LambdaQueryWrapper<TblUser> query = new LambdaQueryWrapper<>();
        query.eq(TblUser::getPhone,phone).orderByDesc(TblUser::getRegisterDatetime).last("limit 1");
        return userMapper.selectOne(query);
    }



    public Map<String,TblUser> getUserListByAppUserIds(List<String> ids) {
        if (ids.isEmpty()) {
            return null;
        }
        QueryWrapper<TblUser> query = new QueryWrapper<>();
        query.in("app_user_id", ids).select("id", "app_user_id", "phone","nickname");
        List<TblUser> tblUsers = userMapper.selectList(query);
        Map<String, TblUser> tblUserMap = new HashMap<>();
        tblUsers.forEach(x->tblUserMap.put(x.getAppUserId().toString(), x));
        return  tblUserMap;
    }

    @Override
    public Page<UserVo> getList(Integer current, Integer pageSize, String phone, Long id, String nickname) throws Exception {

        MPJLambdaWrapper<TblUser> warpper = JoinWrappers.lambda(TblUser.class)
                .selectAll(TblUser.class);
                //.select(TblUserChainAccount::getChainAccount);
               // .leftJoin(TblUserChainAccount.class, TblUserChainAccount::getFkUserId, TblUser::getId);
        if(StringUtils.isNotBlank(phone)) {
            phone = phone.startsWith("86") ? phone : "86" + phone;
            phone = MyAESUtil.encrypt(phone);
            warpper.eq(TblUser::getPhone, phone);
        }
        if(id != null) {
          warpper.eq(TblUser::getAppUserId, id);
        }
        warpper.eq(Objects.nonNull(nickname), TblUser::getNickname, nickname)
                .orderByDesc(TblUser::getId);

        Page<UserVo> userVoPage = userMapper.selectJoinPage(new Page<>(current, pageSize), UserVo.class, warpper);

        List<UserVo> records = userVoPage.getRecords();
         records = records.stream().map(x -> x.setAvatarUri(getAvatarUrl(x.getGender(), x.getAvatarUri()))).toList();
         userVoPage.setRecords(records);
         return userVoPage;
    }


    private String getAvatarUrl(Integer gender, String avatar_uri) {
        if(StringUtils.isBlank(avatar_uri)) {
          if(gender == 0) {
              avatar_uri = this.defaultMale;
          } else if (gender == 1) {
              avatar_uri = this.defaultFemale;
          }
        }
        if(StringUtils.isNotBlank(avatar_uri)) {
           return String.format("%s%s", this.CdnUrl, avatar_uri);
        }
        return  "";
    }
}
